//
//  COServiceTagsView.swift
//  CocoProject
//
//  Created by Vill on 2023/11/13.
//

import UIKit

typealias marketSureBlock = (_ model:MarketQaModel)->Void

class COServiceTagsView: UIView,UICollectionViewDelegate,UICollectionViewDataSource {
    
    var sureBlock:marketSureBlock?
    
    var qaArr:[MarketQaModel] = [MarketQaModel](){
        didSet{
            self.collectionView.reloadData()
        }
    }

    lazy var collectionView: UICollectionView = {
        let flow = XDServiceTagFlowLayout()
        flow.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: PTW(20))
        flow.minimumLineSpacing = PTW(10)
        flow.minimumInteritemSpacing = PTW(10)
        flow.numberOfColumns = 2
        flow.delegate = self
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flow)
        collectionView.backgroundColor = .clear
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(COServiceCollectionViewCell.self, forCellWithReuseIdentifier: "COServiceCollectionViewCell")
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI(){
        self.addSubview(self.collectionView)
        self.collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "COServiceCollectionViewCell", for: indexPath) as! COServiceCollectionViewCell
        let model = self.qaArr[indexPath.item]
        cell.btnStr = model.problem
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.qaArr.count
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.qaArr[indexPath.item]
        if (self.sureBlock != nil){
            self.sureBlock!(model)
        }
    }
}

extension COServiceTagsView:XDServiceTagFlowLayoutDelegate{
    func water(_ layout: XDServiceTagFlowLayout, widthForItem indexPath: IndexPath) -> CGFloat {
        let model = self.qaArr[indexPath.item]
        let strWidth = model.problem.width(withFont:  UIFont.pingfangFont(ofSize: PTW(12), weight: .regular))
        return strWidth + PTW(38)
    }
}
